@extends('layouts.app')
@section('content')
    <img src="https://jcgoing-wechat.oss-cn-guangzhou.aliyuncs.com/images/booked/demo.png" style="width: 100%;height: 100%;max-width:500px;display: none;position: absolute;z-index: 9999;right: -1px;" class="demo-img">
    <form method="post" action="{{ route('Booking.store') }}" accept-charset="UTF-8" enctype="multipart/form-data" >
        {{ csrf_field() }}
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        @include('shared._error')
        @include('shared._messages')
        <div class="form-row">
            <label style="padding:10px 0px 0px 0px;width: 100%;position: relative;"><span class="required-highlight">*</span>进仓单：<button type="button" class="btn btn-xs btn-success img-switch">查看样图</button><button type="button" class="btn btn-xs btn-success preview" onclick="preview()" style="margin-left: 10px;">预览</button></label>
            <div class="custom-file mb-3" onclick="camera()">
                <input type="text" readonly name="files" accept="image/*" required multiple class="custom-file-input" lang="zh" id="validatedCustomFile">
                <label class="custom-file-label" for="validatedCustomFile">进仓单照片一车多票</label>
            </div>
            <div class="form-group col-md-12 col-lg-12 col-sm-12" style="top: 4px;">
                <span class="placeholder-required-highlight" style="left: 9px;">*</span>
                <input type="text" name="name" required class="form-control" value="{{ old('name') }}" placeholder="姓名">
            </div>
        </div>
        <div class="form-group">
            <span class="placeholder-required-highlight">*</span>
            <input type="number" name="phone" required class="form-control" value="{{ old('phone') }}" placeholder="联系电话">
        </div>
        <div class="form-group">
            <span class="placeholder-required-highlight">*</span>
            <input type="text" name="id_card" required class="form-control" value="{{ old('id_card') }}" placeholder="身份证号码">
        </div>
        <div class="form-group">
            <span class="placeholder-required-highlight">*</span>
            <input type="text" class="form-control" readonly autocomplete="off" required name="plate_number" value="{{ old('plate_number') }}" placeholder="车牌号码">
        </div>
        <div class="form-group">
            <span class="placeholder-required-highlight">*</span>
            <input type="date" name="booking_date" value="{{ old('booking_date') }}" required class="form-control date-placeholder">
            <select class="form-control" name="time_range" required style="margin-top: 1rem;height: 45px;background: #F7F7F7;">
                <option value="">请选择时间段</option>
                <option {{ old('timerange') == '08:30 - 11:30' ? 'selected' : '' }} value="08:30 - 11:30">08:30 - 11:30</option>
                <option {{ old('timerange') == '11:31 - 15:00' ? 'selected' : '' }} value="11:31 - 15:00">11:31 - 15:00</option>
                <option {{ old('timerange') == '15:01 - 18:00' ? 'selected' : '' }} value="15:01 - 18:00">15:01 - 18:00</option>
                <option {{ old('timerange') == '18:00 - 20:30（加班）' ? 'selected' : '' }} value="18:00 - 20:30（加班）">18:00 - 20:30（加班）</option>
            </select>
        </div>
        <input type="hidden" name="user_id" value="{{ $user_id }}">
        <button type="submit" class="btn btn-primary btn-lg btn-block">提交</button>
        {{--        <vue-hash-calendar :visible.sync="show" :model="model" @confirm="confirmEvent" format="YY-MM-DD hh:mm"></vue-hash-calendar>--}}
    </form>
    <div class="car_input" style="display: none;">
        <ul class="clearfix ul_input">
            <li class="input_pro"><span></span></li>
            <li class="input_pp input_zim"><span></span></li>
            <li class="input_pp"><span></span></li>
            <li class="input_pp"><span></span></li>
            <li class="input_pp"><span></span></li>
            <li class="input_pp"><span></span></li>
            <li class="input_pp"><span></span></li>
        </ul>
    </div>
@stop
@section('scriptsAfterJs')
    <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="/js/layer_mobile/layer.js" type="text/javascript"></script>
    <script src="/js/plateNumber.js" type="text/javascript"></script>
    <script>
        var base64Data = [];
        var localIds = [];
        var serverIds = [];
        wx.config(<?php echo $config;?>);
        wx.ready(function(){

            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        });
        function camera() { // 拍照上传
            wx.chooseImage({
                count: 5, // 默认9
                sizeType: ['original'],  //'original', 'compressed'可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album','camera'], // 'album', 'camera'可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    base64Data = [];
                    serverIds = [];
                    push(localIds)
                    // urlTobase64(localIds);
                }
            });
        }
        function push(localIds, index) {
            index = index || 0
            wx.uploadImage({
                localId: localIds[index], // 需要上传的图片的本地ID，由chooseImage接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    serverIds.push(res.serverId); // 返回图片的服务器端ID
                    index++
                    if(localIds.length === index){
                        $('.custom-file-label').text('已选择'+serverIds.length+'张图片');
                        $('input[name="files"]').val(serverIds.join('mark-booking'));
                    } else {
                        push(localIds, index)
                    }
                }
            });
        }
        function urlTobase64(url){
            base64Data = [];
            serverIds = [];
            for(let key in url){
                wx.uploadImage({
                    localId: url[key], // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function (res) {
                         serverIds.push(res.serverId); // 返回图片的服务器端ID
                        if(url.length === parseInt(key)+1){
                            $('.custom-file-label').text('已选择'+serverIds.length+'张图片');
                            $('input[name="files"]').val(serverIds.join('mark-booking'));
                        }
                    }
                });
            }
        }

        /*wx.getLocalImgData({
            localId: url[key],//图片的本地ID
            success: function (res) {
                let tempBase64 = res.localData;
                if (tempBase64.indexOf('data:image') != 0) {
                    //判断是否有这样的头部
                    tempBase64 = 'data:image/jpeg;base64,' +  tempBase64
                }
                tempBase64 = tempBase64.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg'); // 此处的localData 就是你所需要的base64位
                base64Data.push(tempBase64);
                if(url.length == parseInt(key)+1){
                    $('.custom-file-label').text('已选择'+base64Data.length+'张图片');
                    $('input[name="files"]').val(base64Data.join('mark-booking'));
                }
            }
        })*/
        function preview(){
            if(localIds.length == 0){
                alert('请选择图片');
                return false;
            }
            wx.previewImage({
                current: localIds[0], // 当前显示图片的http链接
                urls: localIds // 需要预览的图片http链接列表
            })
        }
        $(function(){

            var dtToday = new Date();

            var month = dtToday.getMonth() + 1;
            var day = dtToday.getDate();
            var year = dtToday.getFullYear();
            if(month < 10)
                month = '0' + month.toString();
            if(day < 10)
                day = '0' + day.toString();

            var minDate= year + '-' + month + '-' + day;

            $('input[type=date]').attr('min', minDate);
        })

        var test = document.getElementById('validatedCustomFile');
        test.addEventListener('change', function() {
            var t_files = this.files;
            var str = '';
            for (var i = 0, len = t_files.length; i < len; i++) {
                str += !(i+1 == t_files.length) ? t_files[i].name+',' : t_files[i].name;
            };
            $('.custom-file-label').text(str);
        }, false);

        /*>*/
        /*var phone = document.getElementById('phone').value;
*/

        $('input[name="phone"]').change(function(){
            if(!(/^1[3456789]\d{9}$/.test($(this).val())) && $('form').html().indexOf('alert-danger') < 0){
                append('请输入合法手机号');
            }else if((/^1[3456789]\d{9}$/.test($(this).val()))){
                $('.alert-danger').remove();
            }
        })

        /*let reg_plate_number = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/;

        $('input[name="plate_number"]').change(function(){
            if(!(reg_plate_number.test($(this).val())) && $('form').html().indexOf('alert-danger') < 0){
                append('请输入合法车牌');
            }else if((reg_plate_number.test($(this).val()))){
                $('.alert-danger').remove();
            }
        })*/

        let reg_id_card = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

        $('input[name="id_card"]').change(function(){
            if(!(reg_id_card.test($(this).val())) && $('form').html().indexOf('alert-danger') < 0){
                append('请输入合法身份证');
            }else if((reg_id_card.test($(this).val()))){
                $('.alert-danger').remove();
            }
        })

        let reg_name = /^[\u4E00-\u9FA5]{1,6}$/;

        $('input[name="name"]').change(function(){
            if(!(reg_name.test($(this).val())) && $('form').html().indexOf('alert-danger') < 0){
                append('请输入合法姓名');
            }else if((reg_name.test($(this).val()))){
                $('.alert-danger').remove();
            }
        })

        $('.img-switch').click(function(){
            $('.demo-img').toggle();
        })

        $('.demo-img').click(function(){
            $(this).toggle();
        })

        $('.date-placeholder').click(function(){
            $(this).removeClass('date-placeholder');
        })

        $('.btn-block').click(function () {
            reg();
            if($('form').html().indexOf('alert-danger') >= 0){
                return false;
            }
            $(this).text('正在提交中……')
            setTimeout(function(){
                $('.btn-block').attr('disabled','disabled');
            },100)
        })

        function append(val){
            let content = '<div class="alert alert-danger"><div class="mt-2"><b>验证未通过：</b></div><ul class="mt-2 mb-2"><li><i class="glyphicon glyphicon-remove"></i>'+val+'</li></ul></div';
            $('form').prepend(content);
        }
    </script>
@stop

